package net.ecpt.hrm.services;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ofbiz.autoconfig.auto.EntitySQLProcessor;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.security.Security;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;

import javolution.util.FastList;
import javolution.util.FastMap;

public class HrmReportServices {

    public static String module = HrmReportServices.class.getName();

    public static Map<String, Object> listHrDepartmentByAllHrData(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = ctx.getDelegator();
    	List nfsList= new ArrayList();
    	Security security = ctx.getSecurity();
    	GenericValue userLogin = (GenericValue) context.get("userLogin");
    try {
    	if(security.hasPermission("ALL_HR_DATA", userLogin)) {
    		String parentId = (String) context.get("parentId");
    		 Map parentIdParam=UtilMisc.toMap("parentId", parentId);
    		 List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment",parentIdParam ,
    	    		    null, false);
    		 
    		  for (GenericValue gvHrDepartment : gvHrDepartmentList) {
    	    		String departmentName = gvHrDepartment.getString("name");
    	    		String departmentId = gvHrDepartment.getString("departmentId");
    	    		Map map= UtilMisc.toMap("key", departmentId,"value", departmentId,"text", departmentName,"title", departmentName);
    	    		nfsList.add(gvHrDepartment);
    		  }
    		  
    	}else {
    		String partyId =userLogin.getString("partyId");
    		 GenericValue person = delegator.findOne("Person", UtilMisc.toMap("partyId", partyId), false);
    		 String departmentId = person.getString("departmentId");
    		 GenericValue gvHrDepartment = delegator.findOne("HrDepartment",UtilMisc.toMap("departmentId", departmentId), false);
    		 String departmentName = gvHrDepartment.getString("departmentName");
    		 Map map= UtilMisc.toMap("key", departmentId,"value", departmentId,"text", departmentName,"title", departmentName);
    		 nfsList.add(gvHrDepartment);
    	}
    } catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
        result.put("nfsList", nfsList);// 记录
    	return result;
    }
    
    
    // 1人事统计报告
    // 按BU 统计每月离职人数、入职人数、月初在职人员、月末在职人员（离职率、入职率）
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Object> getEmployeeRecordResignReport(DispatchContext ctx,
	    Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
	
	//参数传入1  全部公司 子公司
	//传入 73 为总部下属部门
	
	
	String parentId = (String) context.get("parentId");
	 Map parentIdParam=UtilMisc.toMap("parentId", parentId);
    
	 String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
	 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
		 parentIdParam.put("departmentId", userLoginDepartmentId);
	 }

	List columns = UtilMisc.toList("序号", "BU", "月份", "离职人数", "入职人数", "月初在职人员", "月末在职人员", "离职率", "入职率");
	List records = new ArrayList();
	try {
    		String setYearMonth = (String) context.get("setYearMonth");//2021-04

    		if(!setYearMonth.contains("-")) {
    			return result;
    		}
    		String[]	setYearMonthArray	=setYearMonth.split("-");
    	int year= Integer.valueOf(setYearMonthArray[0]);
    	int month= Integer.valueOf(setYearMonthArray[1]);
    		Timestamp fromDate =getFirstDayOfMonth(year, month);// 2021-04
    	    Timestamp thruDate =getLastDayOfMonth(year, month);// 2021-04
    	   
    		
    	    
    	    List mainCond1 = new ArrayList();
    	    mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
    	    // 部门列表
    	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment",parentIdParam ,
    		    null, false);

    	    Long resignPersonNumberAll = 0L;
    	    Long buNumAll = 0L;
    	    Long recordPersonNumberAll = 0L;
    	    Long prePersonNumberAll = 0L;
    	    DecimalFormat df = new DecimalFormat("0.00");

    	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
    		String departmentName = gvHrDepartment.getString("name");
    		String departmentId = gvHrDepartment.getString("departmentId");
    		if("73".equals(departmentId)) {
    	    	continue;
    	    }
    	   

    		// 部门离职人数
    		List mainCond2 = new ArrayList();
    		if (UtilValidate.isNotEmpty(fromDate)) {
    		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.GREATER_THAN_EQUAL_TO,
    			    fromDate));
    		}
    		if (UtilValidate.isNotEmpty(thruDate)) {
    		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.LESS_THAN, thruDate));
    		}
    		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
    		mainCond2.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
    		mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
    		Long resignPersonNumber = delegator.findCountByCondition("Person",
    			EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
    		resignPersonNumberAll = resignPersonNumberAll + resignPersonNumber;
    		
    		
    		
    		// 部门入职人数
    		List mainCondRecordPersonNumber = new ArrayList();
    		if (UtilValidate.isNotEmpty(fromDate)) {
    		    mainCondRecordPersonNumber.add(EntityCondition.makeCondition("beginDate", EntityOperator.GREATER_THAN_EQUAL_TO,
    			    fromDate));
    		}
    		if (UtilValidate.isNotEmpty(thruDate)) {
    		    mainCondRecordPersonNumber.add(EntityCondition.makeCondition("beginDate", EntityOperator.LESS_THAN, thruDate));
    		}
    		//mainCondRecordPersonNumber.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
    		mainCondRecordPersonNumber.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
    		mainCondRecordPersonNumber.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
    		Long recordPersonNumber = delegator.findCountByCondition("Person",
    			EntityCondition.makeCondition(mainCondRecordPersonNumber, EntityOperator.AND), null, null);
    		recordPersonNumberAll = recordPersonNumberAll + recordPersonNumber;
    		
    		
    		//1月  10 +1  -2  
    		//2月  9  +2  -1   10
    		
    		// 部门在职人数
    		List mainCond3 = new ArrayList();
    		mainCond3.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
    		mainCond3.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
    		mainCond3.add(EntityCondition.makeCondition("workState", EntityOperator.NOT_EQUAL, "2"));
    		Long buNum = delegator.findCountByCondition("Person",
    			EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, null);

    		buNumAll = buNumAll + buNum;
    		
    		//月初
    		long prePersonNumber =buNum -recordPersonNumber+resignPersonNumber;
    		prePersonNumberAll = prePersonNumberAll + prePersonNumber;

    		String resignRate = "";
    		if (buNum == 0) {
    		    resignRate = "0";
    		} else {
    		    resignRate = df.format((float)resignPersonNumber /(buNum+resignPersonNumber) * 100);
    		}
    		
    		String recordRate = "";
    		if (buNum == 0) {
    			recordRate = "0";
    		} else {
    			recordRate = df.format((float)recordPersonNumber / buNum * 100);
    		}
    		
    		Map record = new HashMap();
    		record.put("departmentId", departmentId);
    		record.put("departmentName", departmentName);
    		
    		record.put("thisMonth", setYearMonth);
    		record.put("resignPersonNumber", resignPersonNumber);
    		record.put("recordPersonNumber", recordPersonNumber);
    		record.put("prePersonNumber", prePersonNumber);
    		record.put("thisPersonNumber", buNum);
    		record.put("resignRate", resignRate + "%");
    		record.put("recordRate", recordRate + "%");


    		records.add(record);
    	    }
    	    // 汇总
    	    String resignRateAll = "";
    	    if (buNumAll == 0) {
    	    	resignRateAll = "0";
    	    } else {
    	    	resignRateAll = df.format((float)resignPersonNumberAll / (buNumAll+resignPersonNumberAll) * 100);
    	    }
    	    
    	    String recordRateAll = "";
    		if (buNumAll == 0) {
    			recordRateAll = "0";
    		} else {
    			recordRateAll = df.format((float)recordPersonNumberAll / buNumAll * 100);
    		}
    	    Map record = new HashMap();
    	   
            record.put("departmentName", "汇总");
    		
    		record.put("thisMonth", setYearMonth);
    		record.put("resignPersonNumber", resignPersonNumberAll);
    		record.put("recordPersonNumber", recordPersonNumberAll);
    		record.put("prePersonNumber", prePersonNumberAll);
    		record.put("thisPersonNumber", buNumAll);
    		record.put("resignRate", resignRateAll + "%");
    		record.put("recordRate", recordRateAll + "%");
    	    records.add(record);

    	    
    	    

    	    Map<String, Object> nfs = FastMap.newInstance();
    	    nfs.put("records", records);
    	    nfs.put("columns", columns);// 列名
    	    result.put("nfs", nfs);// 记录
	   
	
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    
    
    public static Map<String, Object> getEmployeeRecordResignReportMainStore(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	
    	Map serviceContext=context;
    	serviceContext.put("parentId", "73");
    	result =getEmployeeRecordResignReport(ctx, context);
    	return result;
    	
    }
    
    /**
     * 获取指定年月的第一天
     * @param year
     * @param month
     * @return
     */
    private static Timestamp getFirstDayOfMonth(int year, int month) {     
        Calendar cal = Calendar.getInstance();   
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份 
        cal.set(Calendar.MONTH, month-1); 
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数 
        cal.set(Calendar.DAY_OF_MONTH,firstDay);  
         
        Timestamp returnTime = new Timestamp(cal.getTime().getTime());
        return returnTime;  
    }
    
    /**
     * 获取指定年月的最后一天
     * @param year
     * @param month
     * @return
     */
    private static Timestamp getLastDayOfMonth(int year, int month) {     
         Calendar cal = Calendar.getInstance();     
         //设置年份  
         cal.set(Calendar.YEAR, year);  
         //设置月份  
         cal.set(Calendar.MONTH, month-1); 
         //获取某月最大天数
         int lastDay = cal.getActualMaximum(Calendar.DATE);
         //设置日历中月份的最大天数  
         cal.set(Calendar.DAY_OF_MONTH, lastDay);  
         Timestamp returnTime = new Timestamp(cal.getTime().getTime());
         return returnTime;  
     }
  
    
    

    
  
    /**
     * 2 员工属性分析报告】
     * 
     * 
    1、文化程度（饼图）、性别（饼图）、年龄架构（20以下，21-30岁，31-40岁，41-50岁，50+）（饼图）；
    2、部门、员工类型、管培生（默认公司全员人数）可以多选框过滤；
    3、需要控制BU和总部的权限
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> getEmployeeAttributeReport(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	try {

	    Map<String, Object> nfs = FastMap.newInstance();

	    // 文化程度
	    String degreeSql = "select b.description 学历,count(p.tiptop_Degree) 人数 from person p, Data_Dictionary b where work_state !='2' and 1=1 and 2=2 and p.tiptop_Degree=b.dictionary_Code and b.dictionary_Type_Id='EMP_EDUCATION' group by b.description";
	    // 员工性别分析
	    String genderSql = "select b.description 性别,count(p.gender) 人数 from person p, Data_Dictionary b  where work_state !='2' and 1=1 and 2=2 and p.gender=b.dictionary_Code and b.dictionary_Type_Id='USER_SEX'  group by b.description";
	    // 统计员工年龄段
	   // String nianlignduanSql2 = "select '0-20' 年龄段, count(*) 人数 from person where age between 0 and 20 	union all select '21-30' 年龄段, count(*) 人数 from person  where age  between 21 and 30 	union all select '31-40' 年龄段, count(*) 人数 from person  where age  between 31 and 40 	union all select '41-50' 年龄段, count(*) 人数 from person  where age  between 41 and 50 union all select '51-60' 年龄段, count(*) 人数 from person  where age  > 50";
//	    String nianlignduanSql = "select '0-20' 年龄段, count(*) 人数 from person p where work_state !='2' and 1=1 and 2=2 and age between 0 and 20 union all select '21-30' 年龄段, count(*) 人数 from person  where work_state !='2' and 1=1 and 2=2 and age  between 21 and 30 	union all select '31-40' 年龄段, count(*) 人数 from person  where work_state !='2' and 1=1 and 2=2 and age  between 31 and 40 	union all select '41-50' 年龄段, count(*) 人数 from person  where work_state !='2' and 1=1 and 2=2 and age  between 41 and 50 union all select '51-60' 年龄段, count(*) 人数 from person  where work_state !='2' and 1=1 and 2=2 and age  > 50";
	    String nianlignduanSql = "select '0-20' 年龄段, count(*) 人数 from person p where p.work_state !='2' and 1=1 and 2=2 and p.age between 0 and 20 "
	    		     + "union all select '21-30' 年龄段, count(*) 人数 from person p where p.work_state !='2' and 1=1 and 2=2 and p.age  between 21 and 30 "
	    		     + "union all select '31-40' 年龄段, count(*) 人数 from person p where p.work_state !='2' and 1=1 and 2=2 and p.age  between 31 and 40 "
	    		     + "union all select '41-50' 年龄段, count(*) 人数 from person p where p.work_state !='2' and 1=1 and 2=2 and p.age  between 41 and 50 "
	    		     + "union all select '51-60' 年龄段, count(*) 人数 from person p where p.work_state !='2' and 1=1 and 2=2 and p.age  > 50";
	    
	    String ids = (String) context.get("ids");
	    
	    String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
		 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
			 ids=userLoginDepartmentId;
		 }

	    
	    
		if (UtilValidate.isNotEmpty(ids)) {
			ids =getMainStoreSubIds(ids, delegator);
			String p1= "p.department_Id in ("+toSqlInParam(ids)+") ";
			degreeSql =degreeSql.replace("1=1", p1);
			genderSql =genderSql.replace("1=1", p1);
			nianlignduanSql =nianlignduanSql.replaceAll("1=1", p1);
		}
    	String isGuanPeiSheng = (String) context.get("isGuanPeiSheng");//
    	
    	if(UtilValidate.isNotEmpty(isGuanPeiSheng)) {
    		String p2= "p.is_Guan_Pei_Sheng = '"+isGuanPeiSheng+"'";
    		degreeSql =degreeSql.replace("2=2", p2);
    		genderSql =genderSql.replace("2=2", p2);
    		nianlignduanSql =nianlignduanSql.replaceAll("2=2", p2);
    	}
    	 Debug.log("degreeSql:" + degreeSql);
	    Map sqlCommand_degreeSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", degreeSql));
	    Debug.log("sqlCommand_degreeSql:" + sqlCommand_degreeSql);
	    List degreeDataList = (List) sqlCommand_degreeSql.get("records");// 记录
	    List degreeKeyList = (List) sqlCommand_degreeSql.get("columns");// 列名

	    nfs.put("degreeDataList", degreeDataList);
	    nfs.put("degreeKeyList", degreeKeyList);

	    Debug.log("genderSql:" + genderSql);
	    Map sqlCommand_genderSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", genderSql));
	    Debug.log("sqlCommand_genderSql:" + sqlCommand_genderSql);
	    List genderDataList = (List) sqlCommand_genderSql.get("records");// 记录
	    List genderKeyList = (List) sqlCommand_genderSql.get("columns");// 列名

	    nfs.put("genderDataList", genderDataList);
	    nfs.put("genderKeyList", genderKeyList);

	   
	    Debug.log("nianlignduanSql:" + nianlignduanSql);
	    Map sqlCommand_nianlignduanSql = EntitySQLProcessor.executeQuery(delegator,
		    UtilMisc.toMap("sqlCommand", nianlignduanSql));
	    Debug.log(",sqlCommand_nianlignduanSql:" + sqlCommand_nianlignduanSql);
	    List nianlignduanDataList = (List) sqlCommand_nianlignduanSql.get("records");// 记录
	    List nianlignduanKeyList = (List) sqlCommand_nianlignduanSql.get("columns");// 列名

	    nfs.put("nianlignduanDataList", nianlignduanDataList);
	    nfs.put("nianlignduanKeyList", nianlignduanKeyList);

	    result.put("nfs", nfs);// 记录
	    
	   
	} catch (Exception e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    /**
     * 3 管培生毕业学校及对应
 
 注意：这是总部HR的报告。BU没有对应权限。
下拉框选择公司全员、BU，缺省是公司全员
1、上海海事大学，20
2、大连还是大学，18

点击上海海事大学大学，钻取详细列表，
1、where筛选条件：管培生、上海海事大学、在职；
2、缺省排序：入职时间；
3、详单包括：人员，某届，BU，职位，职等，入职时间，学校，学历
     */
    
    public static Map<String, Object> getEmployeeSchoolReport(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = ctx.getDelegator();

    	List columns = UtilMisc.toList("序号", "学校", "人数");
    	List records = new ArrayList();
    	try {
    		
    		String sql ="select p.school 学校,count(p.school) 人数 from person p where work_state !='2' and 1=1 and 2=2 group by p.school  order by count(p.school) desc";
    		
    		String ids = (String) context.get("ids");
    		
    		
    		 String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
    		 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
    			 ids=userLoginDepartmentId;
    		 }
    		if (UtilValidate.isNotEmpty(ids)) {
    			ids =getMainStoreSubIds(ids, delegator);
    			String p1= "p.department_Id in ("+toSqlInParam(ids)+") ";
    			sql =sql.replace("1=1", p1);
    		}
        	String isGuanPeiSheng = (String) context.get("isGuanPeiSheng");//
        	
        	if(UtilValidate.isNotEmpty(isGuanPeiSheng)) {
        		String p2= "p.is_Guan_Pei_Sheng = '"+isGuanPeiSheng+"'";
        		sql =sql.replace("2=2", p2);
        	}
        	
        	
        	int rowLimit = 200;
        	
        	    Map sqlCommand = EntitySQLProcessor.executeQuery(delegator,
        		    UtilMisc.toMap("sqlCommand", sql,"rowLimit",rowLimit));
        	    Debug.log(",sqlCommand_Sql:" + sqlCommand);
        	     records = (List) sqlCommand.get("records");// 记录
        	    //List columns = (List) sqlCommand.get("columns");// 列名

        	  

        	    Map<String, Object> nfs = FastMap.newInstance();
        	    nfs.put("records", records);
        	    nfs.put("columns", columns);// 列名
        	    result.put("nfs", nfs);// 记录
    	   
    	
    	} catch (Exception e) {
    	    Debug.logError(e.getMessage(), module);
    	}
    	return result;
        }
    private static String toSqlInParam(String ids){
    	String result="";
    
    	String[] idsArray =ids.split(";");
    	for(int i=0;i<idsArray.length;i++) {
    		String id=idsArray[i];
    		if(i>0) {result=result+",";}
    		result=result+"'"+id+"'";
    	}
    	return result;
    	
    }
    
    
    
    private static String getMainStoreSubIds(String ids,Delegator delegator) throws GenericEntityException{
    	String result=ids;
    
    	String[] idsArray =ids.split(";");
    	for(int i=0;i<idsArray.length;i++) {
    		String id=idsArray[i];
    		if("73".equals(id)) {
    			List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "73"),null, true);
    			for (GenericValue gvHrDepartment : gvHrDepartmentList) {
            		//String departmentName = gvHrDepartment.getString("name");
            		String departmentId = gvHrDepartment.getString("departmentId");
            		result+=";"+departmentId;
    			}
    			
    			
    		}
    		
    	}
    	return result;
    	
    }
    
    public static List listSubIdMainStoreContain73(){
    	List result=new ArrayList();
    	try {
    	Delegator delegator =DelegatorFactory.getDelegator("default");
    			List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "73"),null, true);
    			for (GenericValue gvHrDepartment : gvHrDepartmentList) {
            		String departmentId = gvHrDepartment.getString("departmentId");
            		result.add(departmentId);
    			}
    			
    			result.add("73");
	    } catch (Exception e) {
		    Debug.logError(e.getMessage(), module);
		}
    	return result;
    	
    }
    
    
    private static String get73SubIds(Delegator delegator) throws GenericEntityException{
    	String result="";
    
    	
    			List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "73"),null, true);
    			for (int i=0;i<gvHrDepartmentList.size();i++) {
    				GenericValue gvHrDepartment =gvHrDepartmentList.get(i);
            		
            		String departmentId = gvHrDepartment.getString("departmentId");
            		if(i>0) {result=result+";";}
            			
            		result=result+departmentId;
    			}
    			
    	
    	
    	return result;
    	
    }
    
    private static List listSubIdMainStore(){
    	List result=new ArrayList();
    	try {
    	Delegator delegator =DelegatorFactory.getDelegator("default");
    			List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "73"),null, true);
    			for (GenericValue gvHrDepartment : gvHrDepartmentList) {
            		String departmentId = gvHrDepartment.getString("departmentId");
            		result.add(departmentId);
    			}
	    } catch (Exception e) {
		    Debug.logError(e.getMessage(), module);
		}
    	return result;
    	
    }
    
    
    
    
//    点击上海海事大学大学，钻取详细列表，
//    1、where筛选条件：管培生、上海海事大学、在职；
//    2、缺省排序：入职时间；
//    3、详单包括：人员，某届，BU，职位，职等，入职时间，学校，学历
    public static Map<String, Object> listEmployeeBySchoolReport(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = ctx.getDelegator();

    	List columns = UtilMisc.toList("序号", "人员", "某届", "BU", "职位", "职等", "入职时间", "学校", "学历");
    	List records = new ArrayList();
    	try {
    		//List<GenericValue> gvHrDepartmentList= new ArrayList();
    		String school = (String) context.get("schoolName");
        	String isGuanPeiSheng = (String) context.get("isGuanPeiSheng");//
        	
        	 // 全部职员列表
        	Map param =UtilMisc.toMap("typeId","EMPLOYEE");
        	if (UtilValidate.isNotEmpty(isGuanPeiSheng)) {
    			param.put("isGuanPeiSheng", isGuanPeiSheng);
    		}
        	if (UtilValidate.isNotEmpty(school)) {
    			param.put("school", school);
    		}
    	     List<GenericValue> personList = delegator.findByAnd("Person",param ,UtilMisc.toList("-createDate"), true);
        		
        	    // 部门列表
//        	    Long personCountAll = 0L;
        	   
        	  
        	    for (GenericValue person : personList) {
        		String personName = person.getString("name");
        		String departmentId = person.getString("departmentId");
        		String departmentName ="";
        		
        		Map record = new HashMap();
        		record.putAll(person);
        		record.put("personName", personName);
        		record.put("departmentId", departmentId);
        		record.put("departmentName", departmentName);

        		records.add(record);
        	    }
        	    
        	    Map<String, Object> nfs = FastMap.newInstance();
        	    nfs.put("records", records);
        	    nfs.put("columns", columns);// 列名
        	    result.put("nfs", nfs);// 记录
    	   
    	
    	} catch (GenericEntityException e) {
    	    Debug.logError(e.getMessage(), module);
    	}
    	return result;
        }
    /**
     * 4 在职员工分析报告
    
     各BU人员占比（各BU的占比饼图）（默认公司全员人数，不区分是否管培生）
1、BU可以多选框过滤；
2、管培生CheckBox选择管培生，则只取管培生的数据。如果不选择这个CheckBox，则不区分管培生；
2、需要控制BU和总部的权限。总部可以查看所有数据。BU只能看到自己的数据；
3、点击BU钻取展开，按照员工类型group by；
4、注意：最下面的汇总不允许点击钻取。
     */
    
    public static Map<String, Object> getBuEmployeeCountReport(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = ctx.getDelegator();

    	List columns = UtilMisc.toList("序号", "BU", "人数");
    	List records = new ArrayList();
    	try {
    		List<GenericValue> gvHrDepartmentList= new ArrayList();
    		String ids = (String) context.get("ids");
    		
    		 String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
    		 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
    			 ids=userLoginDepartmentId;
    		 }
    		
    		
    		String parentId = (String) context.get("parentId");
    		if(UtilValidate.isNotEmpty(parentId)&&("73".equals(parentId))&&UtilValidate.isEmpty(ids)) {
    			ids =get73SubIds(delegator);
    		}
    		
    		List<String> baseIdList = FastList.newInstance();
    		if (UtilValidate.isNotEmpty(ids)) {
    		    baseIdList = Arrays.asList(ids.split(";"));
    		    
    		    List mainCondHrDepartment = new ArrayList();
                mainCondHrDepartment.add(EntityCondition.makeCondition("departmentId", EntityOperator.IN, baseIdList));
             	    
            	 gvHrDepartmentList = delegator.findList("HrDepartment", EntityCondition.makeCondition(mainCondHrDepartment, EntityOperator.AND), null, null, null, true);
            		
    		}else {
    			 gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),null, true);

    		}
    		
    		
        	String isGuanPeiSheng = (String) context.get("isGuanPeiSheng");//
        	
        	 // 全部职员列表
        	Map param =UtilMisc.toMap("typeId","EMPLOYEE");
        	if (UtilValidate.isNotEmpty(isGuanPeiSheng)) {
    			param.put("isGuanPeiSheng", isGuanPeiSheng);
    		}
    	     List<GenericValue> personList = delegator.findByAnd("Person",param ,UtilMisc.toList("-createDate"), true);
        		
        	    // 部门列表
        	   
        	    Long personCountAll = 0L;
        	   
        	  
        	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
        		String departmentName = gvHrDepartment.getString("name");
        		String departmentId = gvHrDepartment.getString("departmentId");
        		
        		// 部门人数
        		 
        		long personCount = buPersonCount( personList, departmentId);
        		personCountAll = personCountAll + personCount;
        		
        		
        		
        		Map record = new HashMap();
        		record.put("departmentId", departmentId);
        		record.put("departmentName", departmentName);
        		
        		record.put("personCount", personCount);
        		


        		records.add(record);
        	    }
        	    // 汇总
        	   
        	    Map record = new HashMap();
        	   
                record.put("departmentName", "汇总");
                record.put("personCount", personCountAll);
               
        	    records.add(record);

        	    
        	    

        	    Map<String, Object> nfs = FastMap.newInstance();
        	    nfs.put("records", records);
        	    nfs.put("columns", columns);// 列名
        	    result.put("nfs", nfs);// 记录
    	   
    	
    	} catch (GenericEntityException e) {
    	    Debug.logError(e.getMessage(), module);
    	}
    	return result;
        }
    
    private static int buPersonCount(List<GenericValue> personList, String thisDepartmentId) {
    	int result = 0;
    	for (GenericValue person : personList) {
    	    String departmentId = person.getString("departmentId");
    	    if (thisDepartmentId.equals(departmentId)) {
    		result = result + 1;
    	    }
    	}
    	
    	if("73".equals(thisDepartmentId)) {
    		List<String> subDepartmentIdList =listSubIdMainStore();
    		for (GenericValue person : personList) {
    			for (String subDepartmentId : subDepartmentIdList) {
        	    String departmentId = person.getString("departmentId");
	        	    if (subDepartmentId.equals(departmentId)) {
	        	    	result = result + 1;
	        	    }
        	    }
    	    }
    	}
    	return result;
    }
    
    
    
    /**
     * 
     * 5  员工类型分布】
     * （汇总才有图）员工类型占比（各类型的占比饼图）（默认公司全员人数，不区分是否管培生）
1、表格形式：
  1.1、BU1，总部定岗，BU定岗，派遣…，汇总；
  1.2、BU2，总部定岗，BU定岗，派遣…，汇总；
  1.3、。。。
  1.4、汇总
2、最下面加汇总字段；
3、BU可以多选框过滤；
4、管培生标签选择管培生，不区分管培生；
5、需要控制BU和总部的权限。总部可以查看所有数据。BU只能看到自己的数据;
6、点击BU钻取展开，按照员工类型group by；
7、注意：最下面的汇总不允许点击钻取。
     */
    
    
    public static Map<String, Object> getEmployeeTypeReport(DispatchContext ctx,
    	    Map<String, ? extends Object> context) {
    	Map<String, Object> result = ServiceUtil.returnSuccess();
    	Delegator delegator = ctx.getDelegator();

    	List columns = UtilMisc.toList("序号", "BU", "总部正式员工", "BU正式员工", "实习生", "派遣工", "临时工", "正式工");
    	List records = new ArrayList();
    	try {
    		List<GenericValue> gvHrDepartmentList= new ArrayList();
    		String ids = (String) context.get("ids");
    		Debug.log("ids ="+ids);
    		
    		 String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
    		 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
    			 ids=userLoginDepartmentId;
    		 }
    		 
    		String parentId = (String) context.get("parentId");
    		if(UtilValidate.isNotEmpty(parentId)&&("73".equals(parentId))&&UtilValidate.isEmpty(ids)) {
    			ids =get73SubIds(delegator);
    		}
    		Debug.log("ids ="+ids);
    		List<String> baseIdList = FastList.newInstance();
    		if (UtilValidate.isNotEmpty(ids)) {
    		    baseIdList = Arrays.asList(ids.split(";"));
    		    Debug.log("baseIdList ="+baseIdList); 
    		    List mainCondHrDepartment = new ArrayList();
                mainCondHrDepartment.add(EntityCondition.makeCondition("departmentId", EntityOperator.IN, baseIdList));
             	    
            	 gvHrDepartmentList = delegator.findList("HrDepartment", EntityCondition.makeCondition(mainCondHrDepartment, EntityOperator.AND), null, null, null, true);
            		
    		}else {
    			 gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),null, true);

    		}
    		
    		
        	String isGuanPeiSheng = (String) context.get("isGuanPeiSheng");//
        	
        		
        	    // 部门列表
        	   
        	    Long c1All = 0L;
        	    Long c2All = 0L;
        	    Long c8All = 0L;
        	    Long c9All = 0L;
        	    Long c10All = 0L;
        	    Long c11All = 0L;
        	    Long totalAll = 0L;
        	    Debug.log("gvHrDepartmentList ="+gvHrDepartmentList); 
        	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
        		String departmentName = gvHrDepartment.getString("name");
        		String departmentId = gvHrDepartment.getString("departmentId");
        		 Long buAll = 0L;
        		// 部门c1人数
        		 
        		long c1Num = buNumByCategoryId( delegator, "1", departmentId,isGuanPeiSheng);
        		c1All = c1All + c1Num;
        		buAll = buAll + c1Num;
        		long c2Num = buNumByCategoryId( delegator, "2",departmentId,isGuanPeiSheng);
        		c2All = c2All + c2Num;
        		buAll = buAll + c2Num;
        		
        		long c8Num = buNumByCategoryId( delegator, "8",departmentId,isGuanPeiSheng);
        		c8All = c8All + c8Num;
        		buAll = buAll + c8Num;
        		long c9Num = buNumByCategoryId( delegator, "9",departmentId,isGuanPeiSheng);
        		c9All = c9All + c9Num;
        		buAll = buAll + c9Num;
        		long c10Num = buNumByCategoryId( delegator, "10",departmentId,isGuanPeiSheng);
        		c10All = c10All + c10Num;
        		buAll = buAll + c10Num;
        		long c11Num = buNumByCategoryId( delegator, "11",departmentId,isGuanPeiSheng);
        		c11All = c11All + c11Num;
        		buAll = buAll + c1Num;
        		
        		
        		Map record = new HashMap();
        		record.put("departmentId", departmentId);
        		record.put("departmentName", departmentName);
        		
        		record.put("c1Num", c1Num);
        		record.put("c2Num", c2Num);
        		record.put("c8Num", c8Num);
        		record.put("c9Num", c9Num);
        		record.put("c10Num", c10Num);
        		record.put("c11Num", c11Num);
        		record.put("buAll", buAll);
        		


        		records.add(record);
        	    }
        	    // 汇总
        	   
        	    Map record = new HashMap();
        	   
                record.put("departmentName", "汇总");
        		
                record.put("c1Num", c1All);
        		record.put("c2Num", c2All);
        		record.put("c8Num", c8All);
        		record.put("c9Num", c9All);
        		record.put("c10Num", c10All);
        		record.put("c11Num", c11All);
        		record.put("buAll", totalAll);
        	    records.add(record);

        	    
        	    

        	    Map<String, Object> nfs = FastMap.newInstance();
        	    nfs.put("records", records);
        	    nfs.put("columns", columns);// 列名
        	    result.put("nfs", nfs);// 记录
    	   
    	
    	} catch (GenericEntityException e) {
    	    Debug.logError(e.getMessage(), module);
    	}
    	return result;
        }
    
    
    private static Long buNumByCategoryId(Delegator delegator,String categoryId,String departmentId,String isGuanPeiSheng) throws GenericEntityException {
    	List mainCond1 = new ArrayList();
		
		mainCond1.add(EntityCondition.makeCondition("categoryId", EntityOperator.EQUALS, categoryId));
		mainCond1.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
		mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		if (UtilValidate.isNotEmpty(isGuanPeiSheng)) {
			mainCond1.add(EntityCondition.makeCondition("isGuanPeiSheng", EntityOperator.EQUALS, isGuanPeiSheng));
		}
		    
		
		Long c1Num = delegator.findCountByCondition("Person",EntityCondition.makeCondition(mainCond1, EntityOperator.AND), null, null);
		
		if("73".equals(departmentId)) {
    		List<String> subDepartmentIdList =listSubIdMainStore();
    		
    			for (String subDepartmentId : subDepartmentIdList) {
    				long subNum =buNumByCategoryId(delegator, categoryId, subDepartmentId, isGuanPeiSheng);
    				c1Num=c1Num+subNum;
    			}
    	    
    	}
		return c1Num;
    }
    
    
    
//  6  人员流失情况
//  时间段选取，按报表展示：
//  部门、职级、员工类型、管培生
//  1、表格形式：
//    1.1、BU1，离职人数，在职人数，离职率（离职人员数量➗全体人员数量，含离职人员）；
//    1.2、BU2，离职人数，在职人数，离职率（离职人员数量➗全体人员数量，含离职人员）；
//    1.3、。。。
//    1.4、汇总
//  2、点击BU钻取展开，按照离职原因group by；
   // 离职原因选项：工作文化、家庭原因、身体原因、薪酬福利、职业发展、管理因素

   @SuppressWarnings({ "rawtypes", "unchecked" })
   public static Map<String, Object> getResignReport(DispatchContext ctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = ctx.getDelegator();
//	List columns = UtilMisc.toList("BU", "离职人数", "在职人数", "离职率");
	List records = new ArrayList();
	try {
	    Timestamp fromDate = (Timestamp) context.get("fromDate");// 2021-04
	    Timestamp thruDate = (Timestamp) context.get("thruDate");// 2021-04
	   // String buId = (String) context.get("departmentId");
	    List mainCond1 = new ArrayList();
	    mainCond1.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
	    
	    String parentId = (String) context.get("parentId");
		
	    String ids = (String) context.get("ids");
	    Debug.log("context ="+context);
	    
	    String userLoginDepartmentId = (String) context.get("userLoginDepartmentId");
		 if(UtilValidate.isNotEmpty(userLoginDepartmentId)) {
			 ids=userLoginDepartmentId;
		 }
		Debug.log("ids ="+ids);
		if(UtilValidate.isNotEmpty(parentId)&&("73".equals(parentId))&&UtilValidate.isEmpty(ids)) {
			ids =get73SubIds(delegator);
		}
	    // 部门列表
//	    List<GenericValue> gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", parentId),
//		    null, false);
	    
		List<GenericValue> gvHrDepartmentList =new ArrayList();
	   
		if (UtilValidate.isNotEmpty(ids)) {
			 List<String> baseIdList = FastList.newInstance();
		    baseIdList = Arrays.asList(ids.split(";"));
		    
		    List mainCondHrDepartment = new ArrayList();
            mainCondHrDepartment.add(EntityCondition.makeCondition("departmentId", EntityOperator.IN, baseIdList));
         	    
        	 gvHrDepartmentList = delegator.findList("HrDepartment", EntityCondition.makeCondition(mainCondHrDepartment, EntityOperator.AND), null, null, null, true);
        		
		}else {
			 gvHrDepartmentList = delegator.findByAnd("HrDepartment", UtilMisc.toMap("parentId", "1"),null, true);

		}
	    
	    
	    
	    
	    

	    Long quitNumAll = 0L;
	    Long buNumAll = 0L;
	    DecimalFormat df = new DecimalFormat("0.00");

	    for (GenericValue gvHrDepartment : gvHrDepartmentList) {
		String departmentName = gvHrDepartment.getString("name");
		String departmentId = gvHrDepartment.getString("departmentId");


		// 部门离职人数
		Long quitNum =  personNumNotWorkDate(delegator, fromDate, thruDate, departmentId);
		
		// 所有部门离职人数
		quitNumAll = quitNumAll + quitNum;
		

		// 部门在职人数
		Long buNum =personNumWorkDate(delegator, fromDate, thruDate, departmentId);
		// 所有部门在职人数
		buNumAll = buNumAll + buNum;
		
		String resignRate = "";
		if (buNum == 0) {
		    resignRate = "0";
		} else {
		    resignRate = df.format((float)quitNum / (buNum+quitNum) * 100);
		}
		
		Map record = new HashMap();
		record.put("departmentId", departmentId);
		record.put("departmentName", departmentName);
		record.put("quitNum", quitNum);
		record.put("onlineNum", buNum);
		record.put("resignRate", resignRate + "%");

		records.add(record);
	    }
	    // 汇总
	    String resignRate = "";
	    if (buNumAll == 0) {
		resignRate = "0";
	    } else {
		resignRate = df.format((float)quitNumAll / (buNumAll+quitNumAll) * 100);
	    }
	    Map record = new HashMap();
	    record.put("departmentName", "汇总");
	    record.put("quitNum", quitNumAll);
	    record.put("onlineNum", buNumAll);
	    record.put("resignRate", resignRate + "%");
	    records.add(record);

	    
	    

	    Map<String, Object> nfs = FastMap.newInstance();
	    nfs.put("records", records);
	 //   nfs.put("buRecords", buRecords);

	    result.put("nfs", nfs);// 记录
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
   }
   
// 部门离职人数
   private static Long personNumNotWorkDate(Delegator delegator, Timestamp fromDate, Timestamp thruDate,String departmentId) throws GenericEntityException{
	   List mainCond2 = new ArrayList();
		if (UtilValidate.isNotEmpty(fromDate)) {
		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.GREATER_THAN_EQUAL_TO,
			    fromDate));
		}
		if (UtilValidate.isNotEmpty(thruDate)) {
		    mainCond2.add(EntityCondition.makeCondition("notWorkDate", EntityOperator.LESS_THAN, thruDate));
		}
		mainCond2.add(EntityCondition.makeCondition("workState", EntityOperator.EQUALS, "2"));
		mainCond2.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
		mainCond2.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		// 部门离职人数
		Long quitNum = delegator.findCountByCondition("Person",
			EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);
		
		if("73".equals(departmentId)) {
    		List<String> subDepartmentIdList =listSubIdMainStore();
    		
    			for (String subDepartmentId : subDepartmentIdList) {
    				long subNum =personNumNotWorkDate(delegator, fromDate, thruDate, subDepartmentId);
    				quitNum=quitNum+subNum;
    			}
    	    
    	}
		
		return quitNum;
   }
   
   // 部门在职人数
   private static Long personNumWorkDate(Delegator delegator, Timestamp fromDate, Timestamp thruDate,String departmentId) throws GenericEntityException{
		
	   List mainCond3 = new ArrayList();
		mainCond3.add(EntityCondition.makeCondition("departmentId", EntityOperator.EQUALS, departmentId));
		mainCond3.add(EntityCondition.makeCondition("typeId", EntityOperator.EQUALS, "EMPLOYEE"));
		mainCond3.add(EntityCondition.makeCondition("workState", EntityOperator.NOT_EQUAL, "2"));
		// 部门在职人数
		Long buNum = delegator.findCountByCondition("Person",
			EntityCondition.makeCondition(mainCond3, EntityOperator.AND), null, null);
		
		if("73".equals(departmentId)) {
    		List<String> subDepartmentIdList =listSubIdMainStore();
    		
    			for (String subDepartmentId : subDepartmentIdList) {
    				long subNum =personNumWorkDate(delegator, fromDate, thruDate, subDepartmentId);
    				buNum=buNum+subNum;
    			}
    	    
    	}
		return buNum;
   }
   
   
   
//6. 2、点击BU钻取展开，按照离职原因group by；
  // 离职原因选项：工作文化、家庭原因、身体原因、薪酬福利、职业发展、管理因素
   public static Map<String, Object> getResignReportByBuId(DispatchContext ctx, Map<String, ? extends Object> context) {
   	Map<String, Object> result = ServiceUtil.returnSuccess();
   	Delegator delegator = ctx.getDelegator();
   	//List records = new ArrayList();
   	try {
   	    Timestamp fromDate = (Timestamp) context.get("fromDate");// 2021-04
   	    Timestamp thruDate = (Timestamp) context.get("thruDate");// 2021-04
   	    String buId = (String) context.get("departmentId");
   	    
   	    
   	    List buRecords = new ArrayList();
   	    if (UtilValidate.isNotEmpty(buId)) {
   		List<GenericValue> stateList = delegator.findByAnd("DataDictionary",
   			UtilMisc.toMap("dictionaryTypeId", "RESIGN_REASON"), UtilMisc.toList("sequenceId"), false);

   		for (GenericValue state : stateList) {
   		    String code = state.getString("dictionaryCode");
   		    String desc = state.getString("description");
   		    // 部门离职人数
   		    List mainCond2 = new ArrayList();
   		    if (UtilValidate.isNotEmpty(fromDate)) {
   			mainCond2.add(EntityCondition.makeCondition("resignDate", EntityOperator.GREATER_THAN_EQUAL_TO,
   				fromDate));
   		    }
   		    if (UtilValidate.isNotEmpty(thruDate)) {
   			mainCond2.add(EntityCondition.makeCondition("resignDate", EntityOperator.LESS_THAN, thruDate));
   		    }
   		    if (!"all".equals(buId)) {
   		       mainCond2.add(EntityCondition.makeCondition("buId", EntityOperator.EQUALS, buId));
   		    }
   		    mainCond2.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "2"));

   		    mainCond2.add(EntityCondition.makeCondition("content", EntityOperator.EQUALS, code));

   		    Long quitNum = delegator.findCountByCondition("HrResign",
   			    EntityCondition.makeCondition(mainCond2, EntityOperator.AND), null, null);

   		    buRecords.add(UtilMisc.toMap("name", desc, "quitNum", quitNum));
   		}
   	    }
   	    Map<String, Object> nfs = FastMap.newInstance();
   	//    nfs.put("records", records);
   	    nfs.put("buRecords", buRecords);

   	    result.put("nfs", nfs);// 记录 
   	    
   	} catch (GenericEntityException e) {
   	    Debug.logError(e.getMessage(), module);
   	}
   	return result;
       }
}
